<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\common\service;

use Exception;
use think\facade\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

/**
 * Token控制器
 */
class Token
{
    //token加密
    public static function encode($data)
    {
        $config = config('jwt');

        $payload = [
            "iss" => $config["iss"], //签发者 可以为空
            "iat" => time(), //签发时间
            "nbf" => time(), //在什么时候jwt开始生效
            "exp" => time() + $config['expire_time'], //token 过期时间
            "data" => $data,
        ];

        return JWT::encode($payload, $config["key"], 'HS256');
    }

    //token解密
    public static function decode()
    {
        $token = Request::header("token");
        $config = config('jwt');
        $status = array("code" => 420);

        $tks = explode('.', $token);

        if (empty($token)) {
            abort(410, 'token为空');
        }

        if (count($tks) != 3) {
            abort(420, 'token格式错误');
        }

        try {
            JWT::$leeway = 60; //当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key($config["key"], 'HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return $arr['data'];
        } catch (Exception $e) {
            abort(420, $e->getMessage());
        }
    }
}